﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Collections.Concurrent;

namespace Development.Tools
{
    /// <summary>
    /// 数据表管理类
    /// </summary>
    public class TableManager : Singleton<TableManager>
    {
        private Dictionary<string, DataFormBase> m_tables = new Dictionary<string, DataFormBase>();
        private FileSystemWatcher m_fileWatcher = null;


        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            var types = Assembly.GetEntryAssembly().GetTypes();
            var baseType = typeof(DataForm<>);
            foreach (var ty in types)
            {
                if (ty.BaseType.Name == baseType.Name)
                {
                   DataFormBase table = Global.CreateObject(ty) as DataFormBase;
                   table.Load(ty.Name.Replace("Table", "Template") + ".xml");
                   m_tables.Add(ty.Name.Replace("Table", ""), table);
                   Log.WriteLog(ELogLevel.LOG_INFO, "load " + ty.Name + " success");
                }
            }
            AddFileWatcher("tables/", "*.xml");
        }

        private void AddFileWatcher(string path,string filter)
        {
            if(m_fileWatcher == null)
            {
                m_fileWatcher = new FileSystemWatcher(path, filter);
                m_fileWatcher.Changed += watcher_Changed;
                m_fileWatcher.EnableRaisingEvents = true;
            }
        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                string tableName = e.Name.Replace("Template.xml", "");
                DataFormBase table = null;
                if (m_tables.TryGetValue(tableName, out table))
                {
                    table.Load(e.Name);
                    Log.WriteLog(ELogLevel.LOG_INFO, "reload " + e.Name + " success");
                }
            }
            catch(Exception ex)
            {
                Log.WriteLog(ELogLevel.LOG_INFO, ex.Message);
            }
           
        }

       



        public T Get<T>(int id) where T : BaseData
        {
            string tableName = typeof(T).Name.Replace("Template", "");
            if(m_tables.ContainsKey(tableName))
            {
                return m_tables[tableName].GetData(id) as T;
            }
            return null;
        }

        public T [] GetTable<T>() where T : BaseData
        {
            string tableName = typeof(T).Name.Replace("Template", "");
            if (m_tables.ContainsKey(tableName))
            {
                return m_tables[tableName].GetTable<T>();
            }
            return null;
        }

      
    }
}
